package com.sxd.service.controller;

import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.sxd.service.domain.User;
import com.sxd.service.service.UserClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;


import java.util.List;

@Controller
@RequestMapping("consumer/user")
@DefaultProperties(defaultFallback = "fallBackMethod")
public class UserController {

    /*@Autowired
    private RestTemplate restTemplate;*/
    /* @Autowired
     private DiscoveryClient discoveryClient; // eureka客户端，可以获取到eureka中服务的信息*/
    @Autowired
    private UserClient userClient;

    /* @GetMapping("/user")
     @ResponseBody
     @HystrixCommand // 标记该方法需要熔断
    // @HystrixCommand(fallbackMethod = "queryUserByIdFallBack")
     public String queryUserById(@RequestParam("id") Long id){
         *//* List<ServiceInstance> instances = discoveryClient.getInstances("service-provider");
        // 因为只有一个Service-provider。所以获取第一个实例
       ServiceInstance instance = instances.get(0);
        // 获取ip和端口信息，拼接成服务地址
        String baseUrl = "http://" + instance.getHost() + ":" + instance.getPort() + "/user/" + id;
        //User user = this.restTemplate.getForObject("http://localhost:8081/user/" + id, User.class);
        User user = this.restTemplate.getForObject(baseUrl, User.class);
        return user;*//*
        if(id == 1){
            throw new RuntimeException("太忙了");
        }
        String baseUrl = "http://service-provider/user/" + id;
        String user = this.restTemplate.getForObject(baseUrl, String.class);
        return user;
    }*/
    @GetMapping
    @ResponseBody
    public User queryUserById(@RequestParam("id") Long id) {
        User user = this.userClient.queryById(id);
        return user;
    }

    public String queryUserByIdFallBack(Long id) {
        return "请求繁忙，请稍后再试！";
    }

    /**
     * 熔断方法
     * 返回值要和被熔断的方法的返回值一致
     * 熔断方法不需要参数
     *
     * @return
     */
    public String fallBackMethod() {
        return "请求繁忙，请稍后再试呀！";
    }
}